import 'package:common_utils/common_utils.dart';
import 'package:currency_balance/bean/invoice_info.dart';
import 'package:currency_balance/view/custom_dialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:qr_flutter/qr_flutter.dart';

import '../bean/balance_detail.dart';
import '../bean/transaction_history.dart';
import '../http/address.dart';
import '../http/http_manager.dart';
import '../view/base_page_loading.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  LoadType loadStatus = LoadType.loading;
  String errorMsg = '';
  BalanceDetail? balanceDetail;
  FlashBalance? flashBalance;
  List<TransactionHistory> historyList = [];
  late TabController controller;
  InvoiceInfo? invoiceInfo;
  // '0xB11C72C3e8150a84e58CC5B3b80B11B3DF04f510'
  // 'ETH'
  @override
  void initState() {
    controller = TabController(length: 2, vsync: this);
    _loadData();
    super.initState();
  }

  void _loadFlashNetwork() {}

  bool isBase64(String str) {
    RegExp exp = RegExp(r'^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$');
    return exp.hasMatch(str);
  }


  Future<void> _loadData() async {
    // String base64Str = 'QkFCQUJBQkEvQlRDLzNMM1c3OXhIa2hSckdlWXlSZ3VqY0JORHJnWkJ3VEFlWEE=';


    String base64Str = Uri.base.path.substring(1);
    if(!isBase64(base64Str)){
      setState(() {
        errorMsg = '参数错误';
        loadStatus = LoadType.loadFailure;
      });

      return;
    }


    Map<String, dynamic>? parameters = {
      'base64': base64Str,
    };

    var result = await HttpManager.getInstance()
        .post(Address.currencyBalanceUrl, null, data: parameters);
    if (result.isSuccess) {
      if (result.data is String) {
        setState(() {
          errorMsg = '查找不到币种信息';
          loadStatus = LoadType.loadFailure;
        });
        return;
      }
      balanceDetail = BalanceDetail.fromJson(result.data);
      if (balanceDetail!.code == 'BTC') {
        var historyResult = await HttpManager.getInstance()
            .get(Address.transactionsUrl, parameters);

        if (historyResult.isSuccess) {
          List historyResponse = historyResult.data;
          historyList =
              historyResponse.map((e) => TransactionHistory.fromJson(e)).toList();
        } else {
          setState(() {
            errorMsg = historyResult.message;
            loadStatus = LoadType.loadFailure;
          });
          return;
        }

        var flashBalanceResult =
        await HttpManager.getInstance().get(Address.balanceUrl, parameters);

        if (flashBalanceResult.isSuccess) {
          flashBalance = FlashBalance.fromJson(flashBalanceResult.data);
        } else {
          setState(() {
            errorMsg = flashBalanceResult.message;
            loadStatus = LoadType.loadFailure;
          });
          return;
        }


        parameters = {
          'amount': 0,
          'base64': base64Str,
        };
        var invoiceResult =
        await HttpManager.getInstance().post(Address.invoiceUrl,null, data: parameters);

        if (invoiceResult.isSuccess) {
          invoiceInfo = InvoiceInfo.fromJson(invoiceResult.data);
          setState(() {
            loadStatus = LoadType.loadSuccess;
          });
        } else {
          setState(() {
            errorMsg = invoiceResult.message;
            loadStatus = LoadType.loadFailure;
          });
        }
      }else{
        setState(() {
          loadStatus = LoadType.loadSuccess;
        });
      }

    } else {
      setState(() {
        errorMsg = result.message;
        loadStatus = LoadType.loadFailure;
      });
      return;
    }


  }

  _showQrCode() {
    showModalBottomSheet(
        context: context,
        builder: (_) {
          return Padding(
            padding: const EdgeInsets.all(20),
            child: Column(
              children: [
                balanceDetail!.code == 'BTC'
                    ? TabBar(
                        unselectedLabelColor: Colors.grey,
                        labelColor: Colors.black,
                        controller: controller,
                        tabs: [
                            Tab(
                              text: 'Lightning',
                            ),
                            Tab(
                              text: balanceDetail!.code,
                            ),
                          ])
                    : SizedBox(),
                balanceDetail!.code == 'BTC'?Expanded(
                  child: TabBarView(controller: controller, children: [
                    _buildFlashDetail(),
                    _buildNormalDetail(),
                  ]),
                ):_buildNormalDetail()
              ],
            ),
          );
        });
  }

  Widget _buildFlashDetail(){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        QrImage(
          data: invoiceInfo!.invoiceUrl,
          version: QrVersions.auto,
          size: 200,
        ),
        SizedBox(
          height: 16,
        ),
        SizedBox(
          width: 90,
          child: ElevatedButton(
              onPressed: () {
                Clipboard.setData(ClipboardData(text: invoiceInfo!.invoiceUrl));
              },
              style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue.withOpacity(0.4),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20))),
              child: Row(children: [
                Icon(
                  Icons.copy,
                  size: 12,
                ),
                SizedBox(
                  width: 4,
                ),
                Text('Copy')
              ])),
        )
      ],
    );
  }

  Widget _buildNormalDetail(){
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        QrImage(
          data: balanceDetail!.address,
          version: QrVersions.auto,
          size: 200,
        ),
        SizedBox(
          height: 16,
        ),
        Text(
          balanceDetail!.address,
          style: TextStyle(color: Colors.grey),
        ),
        SizedBox(
          height: 16,
        ),
        SizedBox(
          width: 90,
          child: ElevatedButton(
              onPressed: () {
                Clipboard.setData(ClipboardData(text: balanceDetail!.address));
              },
              style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue.withOpacity(0.4),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20))),
              child: Row(children: [
                Icon(
                  Icons.copy,
                  size: 12,
                ),
                SizedBox(
                  width: 4,
                ),
                Text('Copy')
              ])),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageDataLoadingView(
        loadStatus: loadStatus,
        errorMsg: errorMsg,
        onLoadSuccess: () {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Align(
                alignment: Alignment.centerLeft,
                child: Padding(
                  padding:
                      EdgeInsets.only(top: 20, right: 20, left: 20, bottom: 10),
                  child: Image(
                    image: AssetImage('assets/images/app_logo.png'),
                    width: 50,
                    height: 50,
                  ),
                ),
              ),
              SizedBox(
                height: 50,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    balanceDetail!.code == 'BTC'
                        ? '${(balanceDetail!.balance * 100000000 + flashBalance!.amountValue).round()}'
                        : balanceDetail!.usd.toString(),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold),
                  ),
                  SizedBox(
                    width: 10,
                  ),
                  Text(
                    balanceDetail!.code == 'BTC' ? 'sat' : 'usdt',
                    style: TextStyle(fontSize: 20, color: Colors.blue),
                  ),
                ],
              ),
              TextButton(
                  onPressed: () => Navigator.of(context).pushNamed(
                      'assetsDetailPage',
                      arguments: {'assetDetail': balanceDetail,'flashAssetDetail':flashBalance,'invoiceInfo':invoiceInfo}),
                  child: Text(
                    'view assets >>',
                    style: TextStyle(color: Colors.grey),
                  )),
              historyList.isEmpty
                  ? Padding(
                      padding: const EdgeInsets.only(top: 40.0),
                      child: Text(
                        'Airchip3 is ready to receive funds.',
                        style: TextStyle(color: Colors.grey),
                      ),
                    )
                  : Builder(
                      builder: (BuildContext context) {
                        final historyItem = historyList.first;
                        return Padding(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 40, vertical: 20.0),
                          child: Column(
                            children: [
                              GestureDetector(
                                  behavior: HitTestBehavior.translucent,
                                  onTap: () => Navigator.of(context).pushNamed(
                                      'assetsHistoryPage',
                                      arguments: {'historyList': historyList}),
                                  child: Text(
                                    'full payment history',
                                    style: TextStyle(color: Colors.grey),
                                  )),
                              SizedBox(
                                height: 16,
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '${historyItem.amountValue} ${historyItem.amountUnit}',
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        color: Colors.grey),
                                  ),
                                  Text(
                                    historyItem.status,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                        color: Colors.grey, fontSize: 12),
                                  )
                                ],
                              ),
                              SizedBox(
                                height: 10,
                              ),
                              Align(
                                alignment: Alignment.centerRight,
                                child: Text(
                                  DateUtil.formatDateMs(historyItem.createTime),
                                  style: TextStyle(
                                      color: Colors.grey, fontSize: 12),
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
              Padding(
                padding: EdgeInsets.only(top: 40),
                child: ElevatedButton(
                    onPressed: _showQrCode,
                    style: ElevatedButton.styleFrom(
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(30))),
                    child: Text('Receive')),
              )
            ],
          );
        },
      ),
    );
  }
}
